

#include "SysTick.h"
#include "LED.h"
#include "USART1.h"


static uint8_t gloop;
static void (*__tick_callback)(void);

void SysTick_Init(void)
{
    SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK);
}


void SysTick_Stop(void)
{
    __tick_callback = 0;
    SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
}




void SysTick_delay_s(uint32_t s, uint8_t loop, void (*_cb)(void))
{
    SysTick_delay_us(s * 1000000, loop, _cb);
}


void SysTick_delay_ms(uint32_t ms, uint8_t loop, void (*_cb)(void))
{
    SysTick_delay_us(ms * 1000, loop, _cb);
}


void SysTick_delay_us(uint32_t us, uint8_t loop, void (*_cb)(void))
{

    gloop = loop;

    __tick_callback = _cb;

    uint32_t ticks = (SystemCoreClock / 1000000) * us;

    SysTick->LOAD  = (uint32_t)(ticks - 1UL);                         /* set reload register */
    NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */
    SysTick->VAL   = 0UL;                                             /* Load the SysTick Counter Value */
    SysTick->CTRL  = SysTick_CTRL_CLKSOURCE_Msk |
                     SysTick_CTRL_TICKINT_Msk   |
                     SysTick_CTRL_ENABLE_Msk;

//    SysTick_Config((SystemCoreClock / 1000000) * us );

}






//Test-------------------------------------


static void Tick_Task()
{

    static uint8_t light = 0;

    if(light)
    {
        light = 0;
        GPIO_ResetBits(GPIOB, GPIO_Pin_0);
    }
    else
    {
        light = 1;
        GPIO_SetBits(GPIOB, GPIO_Pin_0);
    }

}


void SysTick_Test(void)
{
    SysTick_Init();
    SysTick_delay_us(30000000, 1, Tick_Task);
}


void SysTick_Handler(void)
{

    if(__tick_callback)
        __tick_callback();

    if(!gloop)
    {
        __tick_callback = 0;
        SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
    }

}




